from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from .forms import UserRegistrationForm

#首页
def index(request):
    if request.method == 'GET':
        print(request.user)
        return render(request, 'index.html')

#登录
def denglu(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return JsonResponse({'success': True,'username':user.username})
        else:
            return JsonResponse({'success': False,'message':"用户名或者密码错误"})
    return render(request, 'denglu.html')

#注册
def zhuce(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False, 'message': form.errors})
    else:
        form = UserRegistrationForm()
    return render(request, 'zhuce.html', {'form': form})


#注销
def zhuxiao(request):
    logout(request)
    return redirect('index') 



#页面跳转简介
def jianjie(request):
    if request.method == 'GET':
        return render(request, 'jianjie.html')

#页面跳转历史文化
def wenhua(request):
    if request.method == 'GET':
        return render(request, 'wenhua.html')

#页面跳转美食特色
def meishi(request):
    if request.method == 'GET':
        return render(request, 'meishi.html')
    
#页面跳转美食特色
def gonglve(request):
    if request.method == 'GET':
        return render(request, 'gonglve.html')